package org.ai.demo.gateway.filter;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class PreRequestFilter extends ZuulFilter {

    private static final Logger LOG = LoggerFactory.getLogger(PreRequestFilter.class);


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;//int值来定义过滤器的执行顺序，数值越小优先级越高
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LOG.info("send {} request to {}",request.getMethod(),request.getRequestURL().toString());
        
        String requestURI = request.getRequestURI();
		if (requestURI.endsWith("oauth/token")) {
			return null;
		}
		
		String remoteAddr = request.getRemoteAddr();
		Object accessToken = request.getParameter("access_token");
		if(accessToken != null) {
			String[] clientDetail = getClientDetailFromToken(accessToken.toString());
			String clientId = clientDetail[0];
			String clientSecret = clientDetail[1];
			if(!checkIP(clientId, clientSecret, remoteAddr)) {
				LOG.error(remoteAddr + " is not a authorized IP!");
				ctx.setSendZuulResponse(false);
				ctx.setResponseStatusCode(401);
				return null;
			}
		}
		LOG.info("IP check is ok");
        return null;
    }
    
    private boolean checkIP(String clientId, String clientSecret, String remoteAddr) {
    	return true;
    }
    
    private String[] getClientDetailFromToken(String accessToken) {
		String[] tokenStrings = accessToken.split("\\.");
		String[] clientDetail = new String[2];
		clientDetail[0] = decodeBASE64(tokenStrings[1]);
		clientDetail[1] = decodeBASE64(tokenStrings[2]);
		return clientDetail;
		
	}
	
	private  String decodeBASE64(String encodedText){
		final Base64.Decoder decoder = Base64.getDecoder();
		String text = null; 
		try {
			text = new String(decoder.decode(encodedText), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			LOG.error("CustomizedRemoteTokenServices:decodeBASE64" + e.getMessage());;
		}
        return text;
    }
}
